// userPageC/pages/abulkDetail/abulkDetail.js
const app = getApp()
const WXAPI = require('../../../api/api')
const formatTime = require('../../../utils/formatTime.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1,
      // 是否显示左上角图标   1表示显示    0表示不显示
      title: '门店团购',
      // 导航栏 中间的标题
      textColor: '#222',
      // 标题颜色
      bgColor: '#fff',
      // 导航栏背景颜色
      isloading: true,
      isColor: true 
    },
    shopImgList:[
      {id: 0,url:'/images/banner.png'},
      {id: 1,url:'/images/banner.png'},
      {id: 2,url:'/images/banner.png'},
      {id: 3,url:'/images/banner.png'},
    ],
    typeList:[
      {id: 0,value: '套餐详情',hash: 'package'},
      {id: 1,value: '购买须知',hash: 'buy'},
      {id: 2,value: '图文详情',hash: 'graphic'},
    ],
    imgHttp: app.globalData.imgHttp,
    current: 0,
    winHeight: '100%',
    toView: '',//锚点跳转的ID
    actionView: '',//控制导航显示
    packageTop: 0,//商品模块距离顶部的距离
    buyTop: 0,//评价模块距离顶部的距离
    graphicTop: 0,//详情模块距离顶部的
    scrollY: false,
    // 1513441881936760833
    id: '',
    storesData: {},
    phoneList: [],
    phoneShow: false,
    productDetail: [],//套餐详情
    swiperindex: 0,
    grouponId: '',
    setInter: '',
    difference: Number,
    days: '',
    hours:'',
    minutes:'',
    seconds: '',
    shopLnt: app.globalData.lnt,
    shopLat: app.globalData.lat,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var id = options.id
    // id = '1515171525555863554'
    this.getphone()
    this.setData({
      statusHeight: app.gettop.height,
      status: app.gettop.status,
      navHeight: app.gettop.navHeight,
      mobbleBottom: app.mobile.mobbleBottom,
      id: id,
    });
    this.getDetail()
  },
  getDetail(){
    var data = {
      id: this.data.id,
      shopLnt: this.data.shopLnt,
      shopLat: this.data.shopLat
    }
    WXAPI.grouponInfo(data,res => {
      const data = res.result
      if(res.code == 200){
        var productDetail = []
        
        if(data.productDetail){
          productDetail = JSON.parse(data.productDetail)
        }
        this.setData({
          storesData: data,
          productDetail: productDetail,
          phoneList: data.phone.split(',')
        })
        this.countdownTime()
        console.log('phoneList',this.data.phoneList)
        console.log('productDetail',this.data.productDetail)
      }
    })
  },
  //导航到地方
  getLocation:function(){
    const that = this

    wx.getSetting({
      success: (res) => {
      var statu = res.authSetting;
      if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
        // console.log('authSetting:status:拒绝授权后再次进入重新授权', res.authSetting['scope.userLocation'])
        wx.showModal({
          title: '',
          content: '需要获取你的地理位置才能进行导航，请确认授权',
          success: function (res) {
            if (res.cancel) {
              wx.showToast({
                title: '拒绝授权',
                icon: 'none'
              })
            } else if (res.confirm) {
              wx.openSetting({
                success: function (dataAu) {
                  // console.log('dataAu:success', dataAu)
                  if (dataAu.authSetting["scope.userLocation"] == true) {
                    //再次授权，调用wx.getLocation的API
                    that.newgetLocation(dataAu, callback)
                  } else {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none'
                    })
                  }
                }
              })
            }
          }
        })
      } else { 
          that.newgetLocation()
        }
      }
    }) 
  },
  newgetLocation(){
    const storesData = this.data.storesData
    wx.getLocation({
      type: 'gcj02', 
      success: function (res) {
        wx.openLocation({//​使用微信内置地图查看位置。
          latitude: storesData.shopLat,//要去的纬度-地址
          longitude: storesData.shopLnt,//要去的经度-地址
          name: storesData.merchantName,
          address: storesData.locateAddress
        })
      }
    })
  },
  // 倒计时处理方法
  countdownTime(){
    var that = this
    var activityEndTimeStamp = parseInt(this.data.storesData.activityEndTimeStamp)
    var currentTime = Date.now()
    var difference = this.data.difference
    if(difference == 0){
      console.log('已截止');
      clearTimeout(this.data.setInter)
      return
    }
    
    var time = formatTime.intervalTime(currentTime,activityEndTimeStamp)
    console.log('time',time)
    this.setData({
      setInter: setTimeout(that.countdownTime, 1000),
      days: time[0],
      hours: time[1],
      minutes: time[2],
      seconds: time[3],
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.login_dialog = this.selectComponent("#login_dialog");
    console.log('this.login_dialog',this.selectComponent("#login_dialog"))
    var token = wx.getStorageSync('token')
    // 获取各模块距离顶部的距离
    new Promise(resolve => {
      let query = wx.createSelectorQuery();
      query.select('#package').boundingClientRect();
      query.select('#buy').boundingClientRect();
      query.select('#graphic').boundingClientRect();
      query.exec(function (res) {
        resolve(res);
      });
    }).then(res => {
      this.setData({
        packageTop: res[0].top,
        buyTop: res[1].top,
        graphicTop: res[2].top
      });
      // console.log('packageTop',this.data.packageTop)
      // console.log('buyTop',this.data.buyTop)
      // console.log('graphicTop',this.data.graphicTop)
    });
  },
  getphone(){
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        // console.log('res',res)
        var num = app.gettop.height
        if(that.data.scrollY){
          //屏幕的宽度/屏幕的高度 = 微信固定宽度(750)/微信高度
          that.setData({
            winHeight: res.screenHeight-num-50-74+'px'  
          }) 
        }else{
          that.setData({
            winHeight: res.screenHeight-num+'px'  
          }) 
        }
      }   
    });
  },
  scrollTo(e){
    let scrollTop = e.detail.scrollTop+100;  //滚动的Y轴
    if(scrollTop >= this.data.packageTop){
     
      this.setData({
        scrollY: true
      })
    }else{
      this.setData({
        scrollY: false
      })
    }
    this.getphone()
    // console.log('scrollTop',scrollTop)
    if(scrollTop >= this.data.packageTop && scrollTop < this.data.buyTop){
      this.setData({
        current: 0 ,

      })
    }else if(scrollTop >= this.data.buyTop && scrollTop < this.data.graphicTop){
      this.setData({
        current: 1     
      })
    }else if(scrollTop >= this.data.graphicTop){
      this.setData({
        current: 2    
      })
    }
    //this.$apply();//WEPY更新数据
  },
 
  //切换选项
  toViewClick(e){
    const id = e.currentTarget.dataset.id;
    console.log('e',e)
    this.setData({
      current: id,
      toView: e.currentTarget.dataset.hash,  
      actionView: e.currentTarget.dataset.hash
    })
    console.log('toView',this.data.toView)
  },
  //回到首页
  goIndex(){
    wx.switchTab({
      url: '/pages/userMarket/userMarket',
    });
  },
  //立即购买
  handlepay(e){
    const id = e.currentTarget.dataset.id
    this.setData({
      grouponId: id
    })
    const token = wx.getStorageSync('token');
    if(token){
      wx.navigateTo({
        url: '/userPageC/pages/confirmOrder/confirmOrder?grouponId='+this.data.grouponId,
      });
    }else{
      this.login_dialog.loginShow()
    }    
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.setData({
      difference: 0
    });
  },
  endSetInter: function(){
    var that = this;
    //清除计时器  即清除setInter
    clearInterval(that.data.setInter)
  },
  //门店详情  intervalTime
  handleShop(e){
    const shopId = e.currentTarget.dataset.shopid
    const token = wx.getStorageSync('token');
    if(token){
      wx.navigateTo({
        url: '/userPageC/pages/shopBulk/shopBulk?shopId='+shopId,
      });
    }else{
      this.login_dialog.loginShow()
    }  
    
  },
  //
  bindchangeSwiper(e) { 
    this.setData({
      swiperindex: e.detail.current
    })
  },
  //打开电话弹窗
  handlePhoneShow() {
    this.setData({
      phoneShow: !this.data.phoneShow
    });
  },
  //拨打电话
  freeTell(e) {
    var phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    console.log('this.data.id',this.data.id)
    var id = this.data.id
    return {
      title: '门店团购',
      path: '/userPageC/pages/abulkDetail/abulkDetail?id='+id,
    }
  }
})